package com.eat.core;

import java.sql.*;

/**
 * Created by zmy on 2018/4/4.
 */
public class BaseDao {
    private Connection connection;
    private PreparedStatement pstmt;
    private ResultSet rs;

    public int update(String sql, Object... params) {
        int update = 0;
        try {
            // 获取链接
            connection = JdbcUtils.getConnection();
            //创建执行命令的stmt对象
            pstmt = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            // 通过元数据得到占位符参数
            int count = pstmt.getParameterMetaData().getParameterCount();
            // 设置占位符参数
            if (params != null && params.length > 0) {
                for (int i = 0; i < count; i++) {
                    pstmt.setObject(i + 1, params[i]);
                }
            }
            // 执行更新
            update = pstmt.executeUpdate();
            // 获取自增的主键
            ResultSet generatedKeys = pstmt.getGeneratedKeys();
            if (generatedKeys.next()) {
                return generatedKeys.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            JdbcUtils.release(connection, pstmt, null);
        }
        return update;
    }

    public ResultSet executeQuery(String sql, Object... params) {
        connection = JdbcUtils.getConnection();
        try {
            pstmt = connection.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                pstmt.setObject(i + 1, params[i]);
            }
            rs = pstmt.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }

    public void release() {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException("关闭结果集失败", e);
            }
        }
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
                throw new RuntimeException("close PreparedStatement fail", e);
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException("释放连接失败", e);
            }
        }
    }
}
